package com.eurasia.assignment.controller;

import java.util.List;
import java.util.stream.Collectors;

import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PutMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.server.ResponseStatusException;
import org.springframework.web.servlet.support.ServletUriComponentsBuilder;


import com.eurasia.assignment.controller.dto.ClassResponse;
import com.eurasia.assignment.controller.dto.CreateClassRequest;
import com.eurasia.assignment.controller.dto.UpdateClassRequest;
import com.eurasia.assignment.domain.Class;
import com.eurasia.assignment.service.ClassService;

/**
 * 班级控制器
 */
@RestController
@RequestMapping("/classes")
public class ClassController {

    private final ClassService classService;

    public ClassController(ClassService classService) {
        this.classService = classService;
    }

    @PostMapping("")
    public ResponseEntity<ClassResponse> createClass(@RequestBody CreateClassRequest request) {
        
        Class createdClass = classService.createClass(request);
        return ResponseEntity.ok(ClassResponse.fromDomain(createdClass));
    }

    @GetMapping
    public ResponseEntity<List<ClassResponse>> getAllClasses() {
        List<ClassResponse> classes = classService.getAllClasses()
            .stream().map(ClassResponse::fromDomain)
            .collect(Collectors.toList());

        return ResponseEntity.ok(classes);
    }



    /**
     * 根据ID获取班级信息
     */
    @GetMapping("/{id}")
    public ResponseEntity<ClassResponse> getClassById(@PathVariable Long id) {
        return classService.getClassById(id)
                .map(ClassResponse::fromDomain)
                .map(ResponseEntity::ok)
                .orElseThrow(() -> new ResponseStatusException(HttpStatus.NOT_FOUND, "班级不存在，ID: " + id));
    }

    /**
     * 更新班级信息
     * @param id 班级ID
     * @param request 更新请求
     * @return 更新后的班级信息
     */
    @PutMapping("/{id}")
    public ResponseEntity<ClassResponse> updateClass(
            @PathVariable Long id,
            @RequestBody UpdateClassRequest request) {
        try {
            Class updatedClass = classService.updateClass(id, request);
            return ResponseEntity.ok(ClassResponse.fromDomain(updatedClass));
        } catch (IllegalArgumentException e) {
            throw new ResponseStatusException(HttpStatus.BAD_REQUEST, e.getMessage());
        } catch (RuntimeException e) {
            throw new ResponseStatusException(HttpStatus.NOT_FOUND, e.getMessage());
        }
    }
}
